#include "mouse_input.h"
void listen_mice(const char *dev, mouse_event_t *event)
{
    char buf[256];
    int n_len;

    int retval;
    fd_set readfds;
    struct timeval tv;
    int Relative_displacement_X = 0;
    int Relative_displacement_Y = 0;
    unsigned char click_count = 0;

    int fd = open(dev, O_RDONLY);

    if (fd < 0)
    {
        perror(dev);
        return;
    }

    while (1)

    {

        FD_ZERO(&readfds);
        FD_SET(fd, &readfds);
        tv.tv_sec = 20;
        tv.tv_usec = 0;
        if ((retval = select(fd + 1, &readfds, NULL, NULL, NULL)) == 1)
        {
            if ((n_len = read(fd, buf, sizeof(buf))) > 0)
            {
                if (n_len == 3)
                {

                    if ((buf[0] & 0x07) == 1)
                    {
                        ++click_count;
                        if (click_count == 1)
                        {
                            Relative_displacement_X = 0;
                            Relative_displacement_Y = 0;
                            event->x = Relative_displacement_X;
                            event->y = Relative_displacement_Y;
                            sem_post(event->sem);
                        }
                        if (click_count == 2)
                        {
                            event->borad_size_x = Relative_displacement_X;
                            event->borad_size_y = Relative_displacement_Y;
                            sem_post(event->sem);
                        }
                        if (click_count >= 3)
                        {
                            sem_post(event->sem);
                            event->x = Relative_displacement_X;
                            event->y = Relative_displacement_Y;
                        }
                    }
                    else
                    {
                        Relative_displacement_X += buf[1];
                        Relative_displacement_Y += buf[2];
                    }
                }
            }
        }
        else
        {
            break;
        }
    }

    close(fd);
}

void listen_mouse(mouse_event_t *event)
{
    listen_mice("/dev/input/mice", event);
}
